<?php
/**
 * Author: yixuan
 * Time: 2016/5/8 21:02
 **/

namespace app\web\controller;

use app\model\Modules;
use think\Db;
use think\Request;
use think\Validate;

class Platform extends Base
{
    private $all_module;

    public function __construct()
    {
        parent::__construct();
        $this->all_module = Modules::order('id', 'desc')->column('distinct module_name');
        global $_G;
        if (!$_G['isSuperAdmin']) {
            return_msg('无操作权限');
        }
    }

    public function platform()
    {
        //http://d6.dev.yixuan.net/web/index.php?c=site&a=entry&do=platform&m=qq19064&op=display&themeid=1
        global $_G, $_P;
        $do = 'platform';
        $op = !empty($_P['op']) ? $_P['op'] : 'display';
        switch ($op) {
            case 'display':
                return $this->lists();
                break;
            case 'add':
                return $this->add();
                break;
            case 'edit':
                return $this->edit();
                break;
            case 'save':
                return $this->save();
                break;
            case 'set_tmp':    //设置消息模板
            case 'save_tmp':
                return $this->template_msg();
                break;
            case 'delete':
                return $this->del();
                break;
            case 'restore':
                return $this->restore();
                break;
            case 'uploadtxt':
                return $this->uploadtxt();
                break;
            default:
                return $this->lists();
                break;
        }
    }

    public function lists()
    {
        global $_G, $_P;
        $pageNumber = max(1, intval($_P['page']));
        $pageSize = 20;
        $op = 'display';
        $param = input('param.');
        if (isset($param['keyword']) && $param['keyword']) {
            $keyword = $param['keyword'];
            $where = " name like '%{$keyword}%'";
        }
        $sort = isset($param['sort']) && $param['sort'] ? $param['sort'] : 'id';
        $status = isset($_P['status']) && $_P['status'] == 0 ? 0 : 1;
        $total = Db::table('yx_sys_platform')
            ->where('status', $status)
            ->where($where)
            ->count();
        $list = Db::table('yx_sys_platform')
            ->field(['id', 'name', 'logo', 'platform_type', 'token', 'account', 'original', 'appid', 'secret', 'encodingaeskey', 'platform_type', 'isyixuan', 'mchid', 'apikey', 'serial_no', 'use_num', 'status', 'create_time', 'if(isnull(apiclient_cert),0,1) as iscert', 'if(isnull(apiclient_key),0,1) as iscertkey', 'if(isnull(template_msg),0,1) as istmp'])
            ->where('status', $status)
            ->where($where)
            ->order("{$sort} desc")
            ->limit(($pageNumber - 1) * $pageSize, $pageSize)
            ->select();

        $pager = pagination($total, $pageNumber, $pageSize);
        return view('/platform', [
            '_G' => $_G,
            '_P' => $_P,
            'op' => $op,
            'list' => $list,
            'pager' => $pager,
            'total' => $total,
            'pageNumber' => $pageNumber,
            'pageSize' => $pageSize,
            'sort' => $sort,
            'keyword' => $keyword,
            'all_module' => $this->all_module,
        ]);
    }

    public function add()
    {
        global $_G, $_P;
        $op = 'add';
        return view('/platform', [
            '_G' => $_G,
            '_P' => $_P,
            'op' => $op,
            'all_module' => $this->all_module,
        ]);
    }

    public function edit()
    {
        global $_G, $_P;
        $id = $_P['id'];
        $op = 'edit';
        $request = Request::instance();
        $server_url = $request->domain() . '/api.php?id=';
        $item = Db::table('yx_sys_platform')
            ->field(['id', 'name', 'logo', 'platform_type', 'token', 'account', 'original', 'appid', 'secret', 'encodingaeskey',
                "concat('{$server_url}',id) as server_url", 'platform_type', 'isyixuan', 'mchid', 'apikey', 'serial_no', 'use_num', 'status', 'create_time',
                'apiclient_cert', 'apiclient_key', 'template_msg'])
            ->where('id', $id)
            ->find();
        return view('/platform', [
            '_G' => $_G,
            '_P' => $_P,
            'op' => $op,
            'item' => $item,
            'all_module' => $this->all_module,
        ]);
    }

    public function save()
    {
        $post = input('post.');
        if ($post) {
            $rule = [
                'name' => 'require|max:25',
                'platform_type' => 'require|number|between:1,99',
                'account' => 'require',
                'original' => 'require|alphaDash',
                'appid' => 'require|alphaNum',
                'secret' => 'require|alphaNum',
            ];
            $msg = [
                'name.require' => '名称不可为空',
                'name.max' => '名称最多不能超过25个字符',
                'platform_type.require' => '平台类型不可为空',
                'platform_type.number' => '平台类型必须是数字',
                'platform_type.between' => '平台类型必须在1~120之间',
                'account.require' => '账号不可为空',
                'original.require' => '原始ID不可为空',
                'original.alphaDash' => '原始ID只能是字母、数字、下划线、中划线',
                'appid.require' => 'appid不可为空',
                'appid.alphaNum' => 'appid只能是字母、数字',
                'secret.require' => 'appsecret不可为空',
                'secret.alphaNum' => 'appsecret只能是字母、数字'
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($post);

            $errorMsg = '';
            if (!$result) {
                $errorMsg .= $validate->getError() . '<br/>';
            }
            //判断appid是否已存在
            $key = $post['appid'];
            $id = isset($post['id']) && $post['id'] > 0 ? $post['id'] : 0;
            if ($id) {
                $has_appid = Db::table('yx_sys_platform')->where('appid', $key)->where('id', 'neq', $id)->count();
            } else {
                $has_appid = Db::table('yx_sys_platform')->where('appid', $key)->count();
            }

            if ($has_appid > 0) {
                return_tips('该appid已存在', '', 'fail');
            }
            //判断支付参数
            $data = [
                'name' => $post['name'],
                'platform_type' => $post['platform_type'],
                'account' => $post['account'],
                'original' => $post['original'],
                'appid' => $post['appid'],
                'secret' => $post['secret'],
            ];

            $data['logo'] = $this->default_logo($post['platform_type']);
            if (isset($post['mchid']) && $post['mchid']) {
                $rule2 = [
                    'mchid' => 'require|number',
                    'apikey' => 'require|alphaNum',
                ];
                $msg2 = [
                    'mchid.require' => '支付商户号不可为空',
                    'mchid.number' => '支付商户号必须是数字',
                    'apikey.require' => '支付APIKEY不可为空',
                    'apikey.alphaNum' => '支付APIKEY必须是数字',
                ];
                $validate2 = new Validate($rule2, $msg2);
                $result2 = $validate2->check($post);
                if (!$result2) {
                    $errorMsg .= $validate2->getError() . '<br/>';
                }
                $data['mchid'] = $post['mchid'];
                $data['apikey'] = $post['apikey'];
                $data['serial_no'] = isset($post['serial_no']) ? $post['serial_no'] : '';
            }

            $apiclient_cert = request()->file('apiclient_cert');
            if ($apiclient_cert) {// 成功上传后 获取文件内容
                if ($apiclient_cert->validate(['ext' => 'pem'])) {
                    $cert_content = file_get_contents($apiclient_cert->getPathName());
                    $cert_content = authcode($cert_content, 'ENCODE');
                    $data['apiclient_cert'] = $cert_content;
                } else {
                    $errorMsg .= '上传apiclientCert证书格式错误' . '<br/>';
                }
            }

            $apiclient_key = request()->file('apiclient_key');
            if ($apiclient_key) {// 成功上传后 获取文件内容
                if ($apiclient_key->validate(['ext' => 'pem'])) {
                    $key_content = file_get_contents($apiclient_key->getPathName());
                    $key_content = authcode($key_content, 'ENCODE');
                    $data['apiclient_key'] = $key_content;
                } else {
                    $errorMsg .= '上传apiclientKey证书格式错误' . '<br/>';
                }
            }

            if (isset($post['id']) && $post['id'] > 0) {      //编辑
                unset($post['id']);
                $res = Db::table('yx_sys_platform')->where('id', $id)->update($data);
                if ($res !== false) {
                    return_tips($errorMsg ? $errorMsg : '编辑成功', createWebUrl('platform', ['op' => 'display']), 'success');
                } else {
                    return_tips($errorMsg ? $errorMsg : '编辑成功', '', 'error');
                }
            } else {    //添加
                //第一次生成token 和 encodingaeskey
                $data['token'] = generate_random_string(32);
                $data['encodingaeskey'] = generate_random_string(43);
                $data['status'] = 1;
                $data['create_time'] = date('Y-m-d H:i:s', time());
                $res = Db::table('yx_sys_platform')->insert($data);
                if ($res) {
                    return_tips($errorMsg ? $errorMsg : '添加成功', createWebUrl('platform', ['op' => 'display']));
                } else {
                    return_tips($errorMsg ? $errorMsg : '添加失败', '', 'error');
                }
            }
        }
    }

    //消息模板
    public function template_msg()
    {
        global $_G, $_P;
        if (request()->isPost()) {
            // 处理POST请求
            $postData = input('post.');
            if (!isset($postData['id']) || !$postData['id']) {
                return_tips('ID不可为空', '', 'fail');
            }
            // 你的处理代码
            $data['mb_group_success'] = isset($postData['mb_group_success']) ? $postData['mb_group_success'] : '';
            $data['mb_group_goshop'] = isset($postData['mb_group_goshop']) ? $postData['mb_group_goshop'] : '';
            $data['mb_group_progress'] = isset($postData['mb_group_progress']) ? $postData['mb_group_progress'] : '';
            $data['mb_bargain_success'] = isset($postData['mb_bargain_success']) ? $postData['mb_bargain_success'] : '';
            $data['mb_bargain_progress'] = isset($postData['mb_bargain_progress']) ? $postData['mb_bargain_progress'] : '';
            $data['mb_bargain_result'] = isset($postData['mb_bargain_result']) ? $postData['mb_bargain_result'] : '';
            $data['mb_help_success'] = isset($postData['mb_help_success']) ? $postData['mb_help_success'] : '';
            $data['mb_presale_new'] = isset($postData['mb_presale_new']) ? $postData['mb_presale_new'] : '';
            $data['mb_presale_sale'] = isset($postData['mb_presale_sale']) ? $postData['mb_presale_sale'] : '';
            $data['mb_presale_payment'] = isset($postData['mb_presale_payment']) ? $postData['mb_presale_payment'] : '';
            $updateData['template_msg'] = json_encode($data);
            $id = $postData['id'];
            $save = Db::table('yx_sys_platform')->where('id', $id)->update($updateData);
            if ($save !== false) {
                return_tips('保存成功', createWebUrl('platform', ['op' => 'display']));
            } else {
                return_tips('保存失败', '', 'fail');
            }
        } else {
            $op = 'get_tmp';
            $param = input('param.');
            if (isset($param['id']) && $param['id'] > 0) {
                $id = $param['id'];
            } else {
                return_tips('ID不可为空', '', 'fail');
            }
            $info = Db::table('yx_sys_platform')->field('template_msg')->where('id', $id)->find();
            $item = json_decode($info['template_msg'], true);
            return view('/platform', [
                '_G' => $_G,
                '_P' => $_P,
                'id' => $id,
                'op' => $op,
                'item' => $item,
                'all_module' => $this->all_module,
            ]);
        }
    }

    //公众号软删除
    public function del()
    {
        global $_P;
        // 你的处理代码
        $id = $_P['id'];
        $platform = Db::table('yx_sys_platform')->where('id', $id)->find();
        if ($platform['status'] == 0) {
            $save = Db::table('yx_sys_platform')->where('id', $id)->delete();
        } else {
            $save = Db::table('yx_sys_platform')->where('id', $id)->update(['status' => 0]);
        }
        $url = createWebUrl('platform', ['op' => 'display']);
        if ($save) {
            return_tips('删除成功', $url);
        } else {
            return_tips('删除失败', $url);
        }
    }

    public function restore()
    {
        global $_P;
        // 你的处理代码
        $id = $_P['id'];
        $platform = Db::table('yx_sys_platform')->where('id', $id)->find();
        if ($platform['status'] == 0) {
            $save = Db::table('yx_sys_platform')->where('id', $id)->update(['status' => 1]);
        }
        $url = createWebUrl('platform', ['op' => 'display']);
        if ($save) {
            return_tips('还原成功', $url);
        } else {
            return_tips('还原失败', $url);
        }
    }

    //公众号和小程序默认logo
    public function default_logo($platform_type)
    {
        $url = 'http://css2020.yixuan.net/2020css/yx2020/images/';
        if ($platform_type == 1) {
            $name = 'headimg_yx.jpg';
        } else {
            $name = 'headimg_yx_mp.jpg';
        }
        return $url . $name;
    }

    //上传txt
    public function uploadtxt()
    {
        $file = request()->file('file');
        if (!$file->validate(['size' => 33, 'ext' => 'txt'])) {
            $this->return_ajax_json(0, $file->getError());
        }
        $info = $file->move(ROOT_PATH . 'public', '');
        if ($info) {
            $this->return_ajax_json(1, '上传成功');
        } else {
            $this->return_ajax_json(0, $info->getError());
        }
    }

}
